package v1

import (
	"pq/models"
	"sort"

	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"encoding/json"
	"github.com/astaxie/beego"
	"pq/service"
	//"github.com/astaxie/beego"
	"strconv"
)

type TestCategoryController struct {
	TokenCheckController
	//BaseController
}

func (tcc *TestCategoryController) List(){
	limit,_ := tcc.GetInt("limit",0)
	skip,_  := tcc.GetInt("skip",models.MAXROWS)
	cate := new(models.PqTestCategory)
	q:= []interface{}{
		-1,limit,skip,
	}
	cates,count := cate.ListAll(q)
	tm := tcc.GetString("tm")
	if tm == "deep"{
		cs := service.CategoryService{}
		tcc.Response(cs.GetDeepTree(cates,1),len(cates))
		return
	}
	//count := models.GetTotal()
	tcc.Response(cates,count)
}
//当用户选择了考试分类后，获取相关考点分类
func (tcc *TestCategoryController) GetPointsCategory(){
	us := service.UserService{}
	cs := service.TestCategoryService{}
	uid,_ := strconv.Atoi(tcc.Uid)
	user,err := us.GetUserById(uid)
	if err != nil{
		tcc.Fail(err.Error(),"fail")
	}
	//beego.Warning(user.PqTestCategoryId)
	cate,err := cs.GetCategoryById(user.Category_id)
	if err != nil {
		tcc.Fail(err.Error(),"fail")
	}
	cates := cs.GetSettingPointTree(cate.PointSetting)
	tm := tcc.GetString("tm")
	if tm == "deep"{
		cs := service.CategoryService{}
		//make solid ordering
		treeData := cs.GetDeepTree(cates,2)
		sort.Slice(treeData, func(i, j int) bool {
			return treeData[i].Id < treeData[j].Id
		})
		tcc.Response(treeData,len(cates))
		return
	}

	tcc.Response(cates,len(cates))
}
func (tcc *TestCategoryController) ListArea(){
	code := tcc.Ctx.Input.Param(":code")
	if code == "" {
		code = "AREA_ROOT"
	}
	slave := models.GetSlaveDb()
	var cates []orm.Params
	_, _ = slave.Raw(`select  * from pq_test_category where state > -1 and code= ? order by ordering desc`, code).Values(&cates)
	tcc.Response(cates,len(cates))
}
func (tcc *TestCategoryController) ListByCode()  {
	code := tcc.Ctx.Input.Param(":code")
	mode := tcc.GetString("mode")
	//pid,_  := tcc.GetInt("areaId",1)
	slave := models.GetSlaveDb()
	var cates []orm.Params
	var parent models.PqTestCategory
	_ = slave.QueryTable("pq_test_category").Filter("code", code)/*Filter("pid",pid)*/.One(&parent)
	//slave.QueryTable("pq_test_category").Filter("lft__gte",parent.Lft).Filter("rgt__lte",parent.Rgt).Values(&lists)
	if mode == "skiproot" {
		_, _ = slave.Raw(`select  *,if(code='',?,code) as code from pq_test_category where state > -1 and lft > ? and rgt < ? order by level asc,ordering desc`, code, parent.Lft, parent.Rgt).Values(&cates)
	} else {
		_, _ = slave.Raw(`select  *,if(code='',?,code) as code from pq_test_category where state > -1 and lft >= ? and rgt <= ? order by level asc,ordering desc`, code, parent.Lft, parent.Rgt).Values(&cates)
	}
	tm := tcc.GetString("tm")
	if tm == "deep"{
		cs := service.CategoryService{}
		tcc.Response(cs.GetDeepTree(cates,parent.Id),len(cates))
		return
	}
	tcc.Response(cates,len(cates))
}

func (tcc *TestCategoryController) Del()  {
	category := &models.Category{}
	id := tcc.Ctx.Input.Param(":id")
	vid,_ := strconv.Atoi(id)
	_, _ = category.Remove(vid, "pq_test_category")
	tcc.Success("Deleted")
}
func (tcc *TestCategoryController) GetOne(){
	id := tcc.Ctx.Input.Param(":id")
	var nodes []orm.Params
	slave := models.GetSlaveDb()
	//slave.QueryTable("pq_test_category").Filter("id",id).Values(&nodes)
	slave.Raw(`select * from pq_test_category where id =?`,id).Values(&nodes)
	//beego.Warning(nodes)
	tcc.Single(nodes[0])
}
func (tcc *TestCategoryController) Store() {
	node := new(models.PqTestCategory)
	node.Id,_ = tcc.GetInt("id")
	node.Pid,_ = tcc.GetInt("pid")
	node.Title = tcc.GetString("title")
	node.Image = ""
	node.State = 1
	node.Ordering,_ = tcc.GetInt("ordering",0)
	node.Code  = tcc.GetString("code")
	node.Ordering,_ = tcc.GetInt("ordering")
	id := 0
	if node.Id == node.Pid {
		tcc.Fail("父节点不能是自己","")
		return
	}
	if(node.Id > 0) {
		id = node.Id
		master := models.GetMasterDb()
		slave := models.GetSlaveDb()
		var parent models.PqTestCategory
		slave.QueryTable("pq_test_category").Filter("id",node.Pid).One(&parent)

		master.QueryTable("pq_test_category").Filter("id", id).Update(orm.Params{
			"pid" : node.Pid,
			"title" : node.Title,
			"image" : node.Image,
			"code" : node.Code,
			"level":parent.Level+1,
			"ordering" : node.Ordering,
		})

	}else{
		category := &models.Category{}
		newid ,_ := category.Insert(node)
		id = int(newid)
	}

	res := map[string]interface{}{}
	res["id"] = id
	tcc.Single(res)
	//tcc.Success("Category node has created")
}
func (tcc *TestCategoryController) StorePointSetting() {
	//node := new(models.PqTestCategory)
	id,_ := tcc.GetInt("id")

	//node.PointData = tcc.GetString("p")
	master := models.GetMasterDb()
	_, _ = master.QueryTable("pq_test_category").Filter("id", id).Update(orm.Params{
		"point_data": tcc.GetString("p"),
	})
	//_,err := master.Update(node)
	//beego.Warning(err)
	tcc.Success("Saved")
}
func (tcc *TestCategoryController) StorePointSetting2() {
	//node := new(models.PqTestCategory)
	id,_ := tcc.GetInt("id")
	master := models.GetMasterDb()
	_, _ = master.QueryTable("pq_test_category").Filter("id", id).Update(orm.Params{
		"point_setting": tcc.GetString("p"),
	})
	//_,err := master.Update(node)
	//beego.Warning(err)
	tcc.Success("Saved")
}
func (tcc *TestCategoryController) RenSection(){
	p := tcc.GetString("p")
	slave := models.GetSlaveDb()
	var setting map[string]string
	err := json.Unmarshal([]byte(p),&setting)
	if err != nil{
		beego.Warning(err)
	}
	type result struct {
		Id int
		Title string
		Amount int
		Ordering int
		LibType int
	}
	var res []result
	for k,v := range setting {
		var node models.PqTestPointCategory
		r := result{}
		_ = slave.QueryTable("pq_test_point_category").Filter("id", k).One(&node)
		r.Id = node.Id
		r.Title = node.Title
		r.Amount,_ = strconv.Atoi(v)
		r.LibType  = node.LibType
		r.Ordering = node.Ordering
		res = append(res, r)
	}
	tcc.SetServerHeader()
	tcc.Data["json"] = res
	tcc.ServeJSON()

}
func (tcc *TestCategoryController) Option(){
	tcc.Fail("Options invoke","")
}

func (tcc *TestCategoryController) Regenerate(){
	cate := new(models.PqTestCategory)
	cate.ReGenerateTestCategory()
	tcc.Success("重置成功")
}